package com.slkj.shilixiaoyuanapp.ui.teacher.tool.PunchClock;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.support.annotation.NonNull;
import android.widget.TextView;

import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.entity.ToolLocationEntity;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.util.LocationClientUtils;
import com.slkj.shilixiaoyuanapp.view.StateLayout;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

import static com.slkj.shilixiaoyuanapp.entity.code.RxEventProcessorTag.*;

@RuntimePermissions
@ActivityInfo(layout = R.layout.activity_punch_clock, rightHint = "历史记录", title = "教师考勤")
public class PunchClockActivity extends BaseActivity implements ValueAnimator.AnimatorUpdateListener {
    LocationClientUtils locationClientUtils;
    @BindView(R.id.tv_pos)
    TextView tvPos;
    @BindView(R.id.tv_pos_info)
    TextView tvPosInfo;
    @BindView(R.id.tv_num_school)
    TextView tvNum;
    @BindView(R.id.bg_view1)
    TextView bgView1;
    @BindView(R.id.bg_view2)
    TextView bgView2;
    @BindView(R.id.layout_root)
    StateLayout stateLayout;
    double latitude;
    double longitude;
    //定位和获取打卡次数是否成功
    private boolean getPosFinsh = false;
    private boolean getDkNumFinsh = false;
    private int num;
    private boolean isInAnim = false;
    ValueAnimator animatorStart;
    ValueAnimator animatorBack;
    Disposable disposable;
    @Override
    protected void init() {
        RxEventProcessor.get().bind(this);

        locationClientUtils = new LocationClientUtils(aMapLocation -> {
            if (aMapLocation.getErrorCode() == 0) {
                getPosFinsh = true;
                latitude = aMapLocation.getLatitude();
                longitude = aMapLocation.getLongitude();
                tvPos.setText(aMapLocation.getAoiName());
                tvPosInfo.setText(aMapLocation.getAddress());
                checkGetFinsh();
            } else {
                getPosFinsh = false;
                stateLayout.showErrorView();
            }
        });
        PunchClockActivityPermissionsDispatcher.onHaveLocPermissionWithPermissionCheck(this);
        stateLayout.setOnReLoadListener(() -> {
            if (!getPosFinsh) {
                locationClientUtils.start();
            }
            if (!getDkNumFinsh) {
                getNum();
            }
        });
        getNum();
    }

    private void getNum() {
        HttpHeper.get().toolService().getDkNum().compose(bindToLifecycle()).compose(getThread()).subscribe(new CommonCallBack<Integer>() {
            @Override
            public void onCallBackSuccess(Integer data) {
                num = data;
                getDkNumFinsh = true;
                tvNum.setText("第" + num + "次打卡");
                checkGetFinsh();
            }

            @Override
            public void onFail(String mes) {
                showToast(mes);
                getDkNumFinsh = false;
                stateLayout.showErrorView();
            }
        });
    }

    /**
     * 检查定位和获取
     */
    private void checkGetFinsh() {
        if (getPosFinsh && getDkNumFinsh) {
            stateLayout.showContentView();

        }
    }

    @OnClick(R.id.linearLayout2)
    void chosePos() {
        startActivity(ChosePosMapActivity.class);
    }

    @OnClick(R.id.dk)
    void dk() {
        if (!isInAnim) {
            HttpHeper.get().toolService()
                    .dk(num, tvPos.getText().toString(), tvPosInfo.getText().toString())
                    .compose(bindToLifecycle())
                    .compose(getThread())
                    .subscribe(new CommonCallBack<String>(true,this, "打卡中，请稍后") {
                        @Override
                        public void onCallBackSuccess(String data) {
                            LoadSuccessAndFailDialog.showSuccess(PunchClockActivity.this,data);
                            num++;
                            tvNum.setText("打卡成功");
                            showDkFinshAnim();
                        }
                    });
        }
    }

    /**
     * 显示打卡成功的动画
     */
    private void showDkFinshAnim() {
        if (animatorBack == null) {
            animatorStart = ValueAnimator.ofFloat(1f, 1.2f);
            animatorStart.setDuration(1000);
            animatorStart.addUpdateListener(this);
            animatorStart.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) { disposable = Observable.timer(1, TimeUnit.SECONDS)
                            .subscribeOn(Schedulers.io())
                            .observeOn(AndroidSchedulers.mainThread())
                            .doOnComplete(() -> {
                                if (animatorBack == null) {
                                    initEndAnim();
                                }
                                animatorBack.start();
                            }).subscribe();
                }
                @Override
                public void onAnimationStart(Animator animation) {
                    isInAnim = true;

                }
            });
        }
        animatorStart.start();
    }
    private void initEndAnim() {
        animatorBack = ValueAnimator.ofFloat(1.2f, 1f);
        animatorBack.setDuration(1000);
        animatorBack.addUpdateListener(this);
        animatorBack.addListener(new AnimatorListenerAdapter() {
            public void onAnimationEnd(Animator animation) {

                tvNum.setText("第" + num + "次打卡");
                isInAnim = false;
            }
        });
    }
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        float currentValue = (float) animation.getAnimatedValue();
        bgView1.setScaleX(currentValue);
        bgView1.setScaleY(currentValue);
        bgView2.setScaleX(currentValue);
        bgView2.setScaleY(currentValue);
    }

    @Override
    protected void onRightTitleClick() {
        startActivity(PunchClockHistoryActivity.class);
    }

    @Recipient(tag = TOOL_CHOSE_POSTION_FINSH)
    void onPosChecked(ToolLocationEntity locationEntity) {
        latitude = locationEntity.getLat();
        longitude = locationEntity.getLon();
        tvPos.setText(locationEntity.getTitle());
        tvPosInfo.setText(locationEntity.getContent());
    }

    /**
     * 获取定位数据
     */
    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void onHaveLocPermission() {
        locationClientUtils.start();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PunchClockActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void onLocPermissionDenied() {
        showToast("请开启定位权限...");
    }

    @Override
    protected void onDestroy() {
        locationClientUtils.stop();
        RxEventProcessor.get().unBind(this);
        if (animatorStart != null && animatorStart.isRunning()){
            animatorStart.cancel();
        }
        if (animatorBack != null && animatorBack.isRunning()){
            animatorBack.cancel();
        }
        if (disposable != null && !disposable.isDisposed()){
            disposable.dispose();
        }
        locationClientUtils.setLocationListener(null);
        super.onDestroy();

    }
}
